/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.deib.se2.meteocal.gui;

import it.polimi.deib.se2.meteocal.business.boundary.UserManager;
import it.polimi.deib.se2.meteocal.business.entity.User;
import java.io.Serializable;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;


@Named
@SessionScoped
public class FindUserBean implements Serializable{
    private static final long serialVersionUID = 1L;

    @EJB
    private UserManager um;

    private User user;
    private String username;
    @Inject 
    private OthersCalendarBean ocb;
    
    private boolean firstSearch=false;
    
    public FindUserBean(){
        
    }
    
    public String getUsername(){
        return this.username;
    }
    
    public void setUsername(String username){
        this.username = username;
    }
    
    public String findUser() {
        FacesContext context = FacesContext.getCurrentInstance();
        user = um.find(username);
        if(user!=null){
           if(user.getCalendar().isIsPublic()){
              if(!firstSearch){
                  setUser(user);
                  firstSearch =true;
               }else{
                  setUser(user);
                  ocb.setUser(user);
                  ocb.resetCalendar();
                  ocb.insertCalendar();
               }
               return "/user/othersCalendar?faces-redirect=true";
            }else{
                context.addMessage(null, new FacesMessage("User with private calendar"));
                return null;
            }
        }else{
            context.addMessage(null, new FacesMessage("User not found"));
            return null;
        }
        
    }
    public void setUser(User user){
        this.user=user;
    }
    public User getUser(){
        return user;
    }
    
    public void clearUser(){
        this.user= null;
        this.username ="";
    }
    public String returnToHome(){
        clearUser();
        ocb.resetCalendar();
        return "/user/home?faces-redirect=true";
    }
    
}
